/*
 * Copyright 2008 Johnny Jian
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.getris

import com.googlecode.getris.dialog.AboutDialog
import com.googlecode.getris.dialog.HighScoresDialog
import com.googlecode.getris.dialog.NameInputDialog
import com.googlecode.getris.game.color.ColorfulQuadrelUtils
import com.googlecode.getris.panel.InfoPanel
import com.googlecode.getris.panel.PreviewPanel
import com.googlecode.getris.panel.TetrisPanel
import groovy.swing.SwingBuilder
import static java.awt.event.KeyEvent.*
import javax.swing.ImageIcon
import static javax.swing.KeyStroke.getKeyStroke
import javax.swing.WindowConstants

final dataDir = new File(System.getProperty('user.home') as File, '.getris')
final highScoresFile = new File(dataDir, 'highscores.xml')

final saveHighScores = {
	tetris.highScores.saveTo highScoresFile
}
final setPauseText = { text, key ->
	pause*.text = text
	pause*.mnemonic = key
}
final setPauseEnabled = { enabled ->
	pause*.enabled = enabled
}
final setToResume = setPauseText.curry('Resume', VK_R)
final setToPause = setPauseText.curry('Pause', VK_P)
final enablePause = setPauseEnabled.curry(true)
final disablePause = setPauseEnabled.curry(false)

final exitAction = {
	saveHighScores()
	System.exit(0)
}
final aboutAction = {
    new AboutDialog([frame: frame] as Binding).run()
}
final newGameAction = {
	tetris.newGame()
	setToPause()
	enablePause()
}
final pauseAction = {
	if (tetris.running) {
		tetris.pause()
		setToResume()
	}
}
final pauseOrResumeAction = {
	if (tetris.running) {
		tetris.pause()
		setToResume()
	} else if (tetris.paused) {
		tetris.resume()
		setToPause()
	}
}
final highScoresAction = {
    new HighScoresDialog([frame: frame, tetris: tetris] as Binding).run()
}

// changed to use SwingBuilder.lookAndFeel
// UIManager.lookAndFeel = UIManager.systemLookAndFeelClassName
ColorfulQuadrelUtils.registerColorfulQuadrels()
dataDir.mkdir()

pause = []
swing = new SwingBuilder()
swing.lookAndFeel 'system'
frame = swing.frame(
	title: 'Getris',
	size: [370, 460], // XXX: should it be refractored to final variables (also to the other constants) ?
	layout: null, // set for absolute localization. XXX: change to more flexible layout
	locationRelativeTo: null, // set the window to the center of the screen
	resizable: false,
	defaultCloseOperation: WindowConstants.EXIT_ON_CLOSE,
	iconImage: new ImageIcon(getClass().getResource('/icon/getris.gif')).image,
	windowLostFocus: pauseAction,
	windowClosing: saveHighScores
) {
	menuBar {
		menu(text: 'Game', mnemonic: VK_G) {
			menuItem(text: 'New Game', mnemonic: VK_N, accelerator: getKeyStroke('F2'), actionPerformed: newGameAction)
			pause << menuItem(text: 'Pause', mnemonic: VK_P, accelerator: getKeyStroke('F3'), actionPerformed: pauseOrResumeAction, enabled: false)
			separator()
			menuItem(text: 'High Scores', mnemonic: VK_H, actionPerformed: highScoresAction)
			separator()
			menuItem(text: 'Exit', mnemonic: VK_E, accelerator: getKeyStroke('alt F4'), actionPerformed: exitAction)
		}
		menu(text: 'Help', mnemonic: VK_H) {
			menuItem(text: 'About', mnemonic: VK_A, accelerator: getKeyStroke('F1'), actionPerformed: aboutAction)
		}
	}
	tetris = panel(new TetrisPanel(10, 20, 20, 1, 10), location: [20, 0])
	panel(new PreviewPanel(5, 4, 20, tetris), location: [240, 0])
	panel(new InfoPanel(tetris), size: [102, 122], location: [240, 100])
	button(text: 'New Game', mnemonic: VK_N, location: [240, 290], size: [102, 30], actionPerformed: newGameAction)
	pause << button(text: 'Pause', mnemonic: VK_P, location: [240, 330], size: [102, 30], actionPerformed: pauseOrResumeAction, enabled: false)
	button(text: 'Exit', mnemonic: VK_E, location: [240, 370], size: [102, 30], actionPerformed: exitAction)
}
tetris.addGameOverObserver({ o, game ->
	disablePause()
	if (game.highScores.isTopScore(game.scoreKeeper.score)) {
        def dialog = new NameInputDialog([frame: frame] as Binding)
        dialog.run()
        game.highScores << [dialog.name, game.scoreKeeper.score]
	}
} as Observer)
tetris.highScores.loadFrom highScoresFile

frame.visible = true
